package com.nuliji.help;

import com.aliyuncs.exceptions.ClientException;
import com.nuliji.constants.SessionKey;
import com.nuliji.dto.SmsSessionDto;
import com.nuliji.tools.exception.ParameterException;
import com.nuliji.tools.Transform;
import com.nuliji.tools.third.aliyuncs.Aliyun;
import com.nuliji.tools.third.aliyuncs.SendSmsResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Objects;

/**
 * Created by GaoJie on 2017/11/3.
 */
@Service
public class SmsHelp {
    private static final Logger logger = LoggerFactory.getLogger(SmsHelp.class);
    final public String REGISTER_TEMPLATE = "SMS_105270065";
    final public String FORGET_TEMPLATE = "SMS_105305060";
    final private Integer EXPIRE_MINUTES = 15;
    public boolean sendCode(String mobile, String templateId, HttpSession session){
        if(!Objects.equals(templateId, REGISTER_TEMPLATE) && !templateId.equals(FORGET_TEMPLATE))
            throw new ParameterException("手机验证码类型错误");
        int verifyCode = (int) ((Math.random() * 9 + 1) * 100000);
        String code = String.valueOf(verifyCode);

        SmsSessionDto dto = new SmsSessionDto();
        dto.setCode(code);
        dto.setSendMobile(mobile);
        Date date = new Date();
        date.setTime(date.getTime() + EXPIRE_MINUTES*60*1000);
        dto.setExpireTime(date);
        try {
            Object response = Aliyun.sendSms(mobile, templateId, code);
            dto.setResponse(Transform.convert(response, SendSmsResponse.class));
        } catch (ClientException e) {
            logger.error("发送短信失败", e);
            return false;
        }
        session.setAttribute(SessionKey.SMS_KEY, dto);
        return true;
    }

    public boolean verifyCode(String mobile, String code, HttpSession session) {
        SmsSessionDto dto = (SmsSessionDto) session.getAttribute(SessionKey.SMS_KEY);
        if(dto == null){
            throw new ParameterException("手机验证码错误！");
        }
        session.removeAttribute(SessionKey.SMS_KEY);
        String originCode = dto.getCode();
        String originMobile = dto.getSendMobile();
        Date expireTime = dto.getExpireTime();
        if (StringUtils.equalsIgnoreCase(originCode, code) && StringUtils.equalsIgnoreCase(originMobile, mobile)) {
            if (new Date().getTime() > expireTime.getTime()) {
                throw new ParameterException("验证码已过期！");
            }
            return true;
        }
        return false;
    }
}
